import java.security.*;
import java.security.cert.*;
import java.security.spec.*;
import javax.crypto.*;
import java.util.*;
import java.io.*;

/**
 * 验证a7证书和私钥是否匹配
 */
public class VerifyA7Certificate {
    
    // a7证书（Base64编码）
    private static final String A7_CERT_BASE64 = 
        "MIIC6DCCAdCgAwIBAgIGAZlhQblOMA0GCSqGSIb3DQEBCwUAMDUxCzAJBgNVBAYTAkNOMRAwDgYDVQQKEwdFeGFtcGxlMRQwEgYDVQQDEwtTZWxmLVNpZ25lZDAeFw0yNTA5MTkwOTE1MjFaFw0yNjA5MTkwOTE1MjFaMDUxCzAJBgNVBAYTAkNOMRAwDgYDVQQKEwdFeGFtcGxlMRQwEgYDVQQDEwtTZWxmLVNpZ25lZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALPwnK6bMFFHWeN3E/MIWmpZesBQGILjJxNtMN1Z2lmRyLCJdTmz87EXmLuX4e/Bz0aCOmH88qjs+laHFmnPIQal3rJU32MCMk63bejZN6yArwv8MAyF0kvyA3EoBC6ZsYX55sxtxLyNYvG8MCqmacRbxV0IsSMXq6o4+1wOYiQEXzdbqhp67fYPNOv81LXqxQZArGV+Wj2o86XtW1wixtHnaSUori4jJjbe1YKi6LIbzhz9SK34+V4PkRhQYS7ensgAAbm4k3N5R3RSNkOHLrHu576QaBwKYI1DjNJL9tAcySdqXColS9RLG0h/x2r78Pvybt3hm32f1kPbu3hnaMcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEApMy1ilW+EsqQZ+2VMyvmQgjfqoaat5kvNqdluLwtzISuY/dv1V2ccR3eShnta7hKO1WCT1WF3L31MLtDwWw/VEiWFDu3+H/9P9nWr7w6ocGVWCUwUoZwiJk5DuBKZYlmj8LgjAKk6bh3hi7Fs3Kbct1rLXUtL0wiqRF7y49tnjWKiEOzgIeHQnS6m2geS1aEpUQlsEm8vUanNuAmnWJppMpfJuWQ7XDPZfRDelyepkefWSdOtd3RKKWGhk70KM00Scmav4mrUYE1K8xIXUvYrc2EC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o/qv0269jtmCP7IqkGMdhTQrVetTHjZNZJH2bvUZ4o/0YT2+TTFPIkTb2/a0txUTBTKrbnAdXh/iPFZAGvBROEDN0MNKo/vGAfi0K836DeTyBIaYongm66Rn6pwnUTQKBgBveVaougfoxAhIbSrWuISCH8xjsE6nSA+G/Aj5Uwq8u1TzgVlWxkHLIgQVZt0sImfSufJ/kr7eJt42WgRJSoAmedC4mCBSbh8bxI+lEne+MC5TS9UDi/Ly0c/1cL8vQna93ScEcO4YMbJ97U1NBdyvx+eR4U/C89lDJ8YGHa9gzAoGAQ6sYsHFCXOKyDeTDoFyEUYgKqrzhT7/HaofR4Oy2OEBZKUl4anx2WnvC/+m3FG6mY7JoovuT29mABXCe+khR9aO8tBpy/WGa4t2B4nse1e8WIehp4i5kOuSKfZFVFUN+Kv3JRHMtakmO/v9JLHZlBhT8U9hh61GygOJ6gYdTiN0CgYAFz9iPy/xqLOUwiTNp3ImzhdZo9ol3Qlr9CfMWMFHqRA5AyYvly9ZzxTpUCpSA+qz6OXqAjJ0bhGQxW2KHpmcTyNGOPPca2vCaW8Mb1NTQueXpUBqX7alIkrRjUUyULteLb8FtyYl7mR3TVIu3FoO5anNwDZ+2y7R9WUEiOzY3NA==";
    
    public static void main(String[] args) {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("            验证a7证书和私钥是否匹配");
        System.out.println("=".repeat(80) + "\n");
        
        try {
            // 解析证书
            byte[] certBytes = Base64.getDecoder().decode(A7_CERT_BASE64);
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
                new ByteArrayInputStream(certBytes)
            );
            
            System.out.println("✅ 证书信息:");
            System.out.println("  Subject: " + cert.getSubjectDN());
            System.out.println("  Issuer: " + cert.getIssuerDN());
            System.out.println("  Serial: " + cert.getSerialNumber().toString(16));
            System.out.println("  Valid From: " + cert.getNotBefore());
            System.out.println("  Valid To: " + cert.getNotAfter());
            
            PublicKey publicKey = cert.getPublicKey();
            System.out.println("  Public Key Algorithm: " + publicKey.getAlgorithm());
            System.out.println("  Public Key Format: " + publicKey.getFormat());
            
            // 提取公钥模数
            if (publicKey instanceof java.security.interfaces.RSAPublicKey) {
                java.security.interfaces.RSAPublicKey rsaPubKey = 
                    (java.security.interfaces.RSAPublicKey) publicKey;
                System.out.println("  RSA Modulus (前32字节): " + 
                    bytesToHex(Arrays.copyOfRange(rsaPubKey.getModulus().toByteArray(), 0, 32)));
                System.out.println("  RSA Exponent: " + rsaPubKey.getPublicExponent());
            }
            
            // 解析私钥
            System.out.println("\n✅ 私钥信息:");
            byte[] privateKeyBytes = Base64.getDecoder().decode(PRIVATE_KEY_BASE64);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            
            System.out.println("  Algorithm: " + privateKey.getAlgorithm());
            System.out.println("  Format: " + privateKey.getFormat());
            
            // 提取私钥模数
            if (privateKey instanceof java.security.interfaces.RSAPrivateKey) {
                java.security.interfaces.RSAPrivateKey rsaPrivKey = 
                    (java.security.interfaces.RSAPrivateKey) privateKey;
                System.out.println("  RSA Modulus (前32字节): " + 
                    bytesToHex(Arrays.copyOfRange(rsaPrivKey.getModulus().toByteArray(), 0, 32)));
            }
            
            // 验证密钥对是否匹配
            System.out.println("\n" + "-".repeat(80));
            System.out.println("验证密钥对匹配性...");
            System.out.println("-".repeat(80));
            
            // 测试：用公钥加密，私钥解密
            String testMessage = "Test Message for EP Encryption";
            byte[] testBytes = testMessage.getBytes("UTF-8");
            
            Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encrypted = encryptCipher.doFinal(testBytes);
            
            Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decrypted = decryptCipher.doFinal(encrypted);
            
            String decryptedMessage = new String(decrypted, "UTF-8");
            
            if (testMessage.equals(decryptedMessage)) {
                System.out.println("✅ 密钥对匹配！公钥和私钥是一对！");
                System.out.println("  原始消息: " + testMessage);
                System.out.println("  解密消息: " + decryptedMessage);
            } else {
                System.out.println("❌ 密钥对不匹配！");
            }
            
        } catch (Exception e) {
            System.err.println("❌ 错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

